package com.wocai.jrt.orgadmin.appointment.action;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.orgadmin.appointment.bean.AppointmentResBean;
import com.wocai.jrt.orgadmin.appointment.bean.EmpGroupBreifBean;
import com.wocai.jrt.orgadmin.appointment.bean.InvestorBreifBean;
import com.wocai.jrt.orgadmin.appointment.model.Appointment;
import com.wocai.jrt.orgadmin.appointment.service.spi.AppointmentService;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.investor.bean.MatchReqBean;
import com.wocai.jrt.orgadmin.investor.bean.RelationResBean;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.message.model.MessageLog;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.MessagePush;
import com.wocai.jrt.orgadmin.utils.SmsUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;


/**
 * 预约单控制器
 * @author zhangyz
 * @date 2015-8-17 14:27:16
 */
@Controller
@RequestMapping("/appointment")
public class AppointmentAction extends GenericAction<Appointment> {
	private static final Logger LOGGER = LoggerFactory.getLogger(AppointmentAction.class);
	
	@Inject
	private AppointmentService appointmentServiceImpl;
	@Inject
	private InvestorService investorServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private MessageLogService messageLogServiceImpl;
	@Inject
	private EmployeeService employeeServiceImpl;
	
	/**
	 * 测试生日提醒
	 */
	@RequestMapping("/testBirth")
	public String testBirth() {
		return appointmentServiceImpl.investorBirthTask();
	}
	
	/**
	 * 测试订单逾期提醒
	 */
	@RequestMapping("/testNonPay")
	public String testNonPay() {
		return appointmentServiceImpl.nonPayOrdersRemindTask();
	}
	
	/**
	 * 测试订单兑付提醒
	 */
	@RequestMapping("/testMaturity")
	public void testMaturity() {
		appointmentServiceImpl.orderMaturityTask();
	}
	
	
	/**
     * 获得预约单List，初始化列表页。
     * @param model 参数
     * @return 预约单List
     */
    @RequestMapping("/list")
    public String list(Appointment model, Map<String, Object> maps) {
    	try {
    		List<Appointment> list = appointmentServiceImpl.pagedList(model);
            maps.put("list", list);
		} catch (Exception e) {
			LOGGER.error("get Appointment list error, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "appointment/list";
    }
	
	/**
	 * 获得预约单List，Json格式。
	 * @param model 参数
	 * @return 预约单List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody Appointment model) {
		Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		Date date = model.getEndTime();
    		if (date!=null) {
    			model.setEndTime(new DateTime(date).plusHours(23).plusMinutes(59).plusSeconds(59).toDate());
			}
    		//获取当前机构ID
		    model.setOrgId(UserUtils.getOrgId());
		    String groups = model.getGroupId();
		    if (groups!= null && !groups.equals("")) {
		    	 List<String> groupList = new ArrayList<String>();
				    String [] str = groups.split(",");
				    for (String string : str) {
				    	groupList.add(string);
					}
				    model.setGroupIdList(groupList);
			}
		    model.setOrderBy("FIELD(a.state,0,1,3,2) asc ,appoint_time desc ");
		    LOGGER.info("appointment query list,param=[{}].",JSON.toJSONString(model));
    		List<AppointmentResBean> list = appointmentServiceImpl.queryMyList(model);
    		// 统计的时候，不需要分页
    		model.setPage(null);
    		long totalRecord  = appointmentServiceImpl.queryMyList(model).size();
    		result.put("aaData", list); // 返回的数据
    	    result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("appointment query error, msg=[{}]", e.getMessage());
		}
        return result;
	}
		
	  /**
     * 查询机构下的投资人。
     * @param employeeKey
     * @return List<EmpBreifBean>
     */
    @ResponseBody
    @RequestMapping("/investor/{investorKey}")
    public List<InvestorBreifBean> investor(@PathVariable("investorKey") String investorKey) {
    	try {
    		 //查询该机构下所有投资人列表
    		LOGGER.info("query investor in org,param=[{}].",JSON.toJSONString(investorKey));
            List<InvestorBreifBean> eBean = appointmentServiceImpl.getOrgInvestorList(UserUtils.getOrgId(),investorKey);
            List<InvestorBreifBean> temp = new ArrayList<InvestorBreifBean>();
            if (eBean.size() >10) {
            	for (int j = 0; j < 10; j++) {
            		temp.add(eBean.get(j));
				}
			}else {
				temp = eBean;
			}
            return temp;
		} catch (Exception e) {
            LOGGER.error("query investor in org, errorMsg=[{}].", e.getMessage());
		}
        return null;
    }
    /**
     * 预约金额校验
     * @param model 
     * @return boolean
     */
    @ResponseBody
    @RequestMapping("/check")
    public boolean check(Appointment model, Integer type) {
    	if (type == null) {
    		return false;
    	}
    	BigDecimal decimal = model.getOrderAmount();
    	if(decimal == null){
    		return true;
    	}
    	model.setOrgId(UserUtils.getOrgId());
    	//如果投资人id不为空，则是修改投资人详情
    	String productId = model.getProductId();
    	if (StringUtils.isNotBlank(productId)) {
    		Product product =productServiceImpl.get(productId);
    		if (product == null) {
    			return false;
    		}
    		//保留两位小数精度
    		DecimalFormat   df   =new DecimalFormat("#.00");  
    		String douStr = df.format(product.getSubStart());
    		String avaStr = df.format(product.getAvailable());
    		BigDecimal b = new BigDecimal(douStr);  
    		BigDecimal a = new BigDecimal(avaStr);  
    		if(decimal.compareTo(a) == 1 || decimal.compareTo(b)== -1){
    			return false;
    		}
   		return true;
    	} else {
    		return true;
    	}
    }
	
	/**
     * 跳转到新增页面
     * @return 新增页面逻辑视图
     */
    @RequestMapping("/add")
    public String add(Map<String, Object> maps) {
    	try {
    		Product product = new Product();
        	product.setOrgId(UserUtils.getOrgId());
        	//获取机构下可买产品
        	LOGGER.info("add init error, param=[{}].", JSON.toJSONString(product));
        	List<Product> productList = productServiceImpl.getBuyableProducts(product);
        	maps.put("productList", productList);
		} catch (Exception e) {
			LOGGER.error("add init error, errorMsg=[{}].", e.getMessage());
		}
        return "appointment/add";
    }
    
    
    /**
     * 执行实际的新增操作
     * @param model 要新增的数据
     * @return 新增页面逻辑视图
     */
    @ResponseBody
    @RequestMapping("/doAdd")
    public JsonBean doAdd(@RequestBody@Valid Appointment model, BindingResult errors) {
    	JsonBean bean = new JsonBean();
    	String orgId = UserUtils.getOrgId();
    	model.setId(ObjectId.get().toString());
    	model.setCreateTime(new Date());
    	model.setOrgId(orgId);
    	model.setState(0);
    	try {
    		if (errors.hasErrors()) {
				bean.setMessage("参数错误");
				return bean;
			}
    		Appointment temp = new Appointment();
    		temp.setInvestorId(model.getInvestorId());
    		temp.setProductId(model.getProductId());
    		temp.setOrgId(orgId);
    		temp.setState(0);
    		List<Appointment> exist = appointmentServiceImpl.pagedList(temp);
    		if(exist.size() > 0){
    			 bean.setMessage("新增预约失败，该客户对该产品已经有相应未处理的预约单!");
                 bean.setCode(0);
                 return bean;
    		}
    		LOGGER.info("doAdd appointment request,param=[{}].",JSON.toJSONString(model));
    		int result = appointmentServiceImpl.save(model);
            if (result == 1) {
                bean.setMessage("新增预约成功");
                bean.setCode(1);
            } else {
                bean.setMessage("新增预约失败!");
                LOGGER.error("save record error.");
            }
		} catch (Exception e) {
			LOGGER.error("doAdd appointment error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("新增预约失败!");
		}
        return bean;
    }
    
    /**
     * 取消预约单
     * @param model 查询参数，携带ID
     * @return JsonBean
     */
    @ResponseBody
    @RequestMapping("/cancel")
    public JsonBean cancel(@RequestBody Appointment model) {
    	JsonBean bean = new JsonBean();
    	try {
    		String id = model.getId();
    		if (StringUtils.isBlank(id)) {
    			bean.setMessage("参数错误");
    			return bean;
			}
    		model.setCompleteTime(new Date());
    		LOGGER.info("cancel appointment request,param=[{}].",JSON.toJSONString(model));
    		int result = appointmentServiceImpl.appointmentCancel(model);
    		 if (result == 1) {
                 bean.setMessage("取消预约成功");
                 LOGGER.info("cancel appointment success.");
             } else {
                 bean.setMessage("取消预约失败!");
                 LOGGER.error("cancel appointment error.");
             }
		} catch (Exception e) {
			LOGGER.error("cancel appointment error, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    
    /**
     * 处理预约单
     * @param model 查询参数，携带ID
     * @return JsonBean
     */
    @ResponseBody
    @RequestMapping("/deal")
    public JsonBean deal(@RequestBody Appointment model) {
    	JsonBean bean = new JsonBean();
    	try {
    		if (StringUtils.isBlank( model.getId()) || StringUtils.isBlank(model.getOpinion())) {
    			bean.setMessage("参数错误");
    			return bean;
			}
    		model.setCompleteTime(new Date());
    		LOGGER.info("deal appointment request,param=[{}].",JSON.toJSONString(model));
    		int result = appointmentServiceImpl.appointmentDeal(model);
    		 if (result == 1) {
                 bean.setMessage("处理预约成功");
                 LOGGER.info("deal appointment success.");
             } else {
                 bean.setMessage("处理预约失败!");
                 LOGGER.error("deal appointment error.");
             }
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("deal appointment error, errorMsg=[{}].", e.getMessage());
		}
        return bean;
    }
    /**
     * 查看预约单详情页。
     * @param model 查询参数，携带ID
     * @return 预约单详情页
     */
    @RequestMapping("/detail/{id}")
    public String detail(@PathVariable("id")String id, Map<String, Object> maps) {
    	try {
    		Appointment model = appointmentServiceImpl.get(id);
    		//查询投资人信息
    		Investor investor = investorServiceImpl.get(model.getInvestorId());
    		if (investor!=null) {
				model.setInvestorName(investor.getName());
				model.setMobile(investor.getMobile());
				model.setBelongEmpId(investor.getEmployeeId());
			}
    		//查询理财师团队信息
    		EmpGroupBreifBean emp = appointmentServiceImpl.getEmpGroupInfo(model.getEmployeeId());
    		if (emp != null) {
    			model.setGroupName(emp.getGroupName());
			}
            maps.put("model", model);//将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "appointment/detail";
    }
    	
	 /**
     * 给预约单分配理财师
     * @param MatchReqBean matchReqBean
     * @return JsonBean
     */
	@ResponseBody
    @RequestMapping("/allotEmp")
    public JsonBean allotEmp(@RequestBody MatchReqBean matchReqBean) {
		JsonBean bean = new JsonBean();
    	try {
    		 LOGGER.info("allotEmp appointment request,param=[{}].",JSON.toJSONString(matchReqBean));
    		 boolean bool = appointmentServiceImpl.allotEmp(matchReqBean);
    		 if (bool) {
    			 Employee emp =employeeServiceImpl.get(matchReqBean.getEmployeeId());
    			 bean.setMessage("预约单分配理财师成功");
    			//保存预约分配消息日志
    			MessageLog message = new MessageLog();
 				message.setId(ObjectId.get().toString());
 				message.setEmployeeId(matchReqBean.getEmployeeId());
 				message.setSender("机构消息");
 				message.setSource("Pad端");
 				message.setSkipType(2);
 				message.setSkipKey(matchReqBean.getId());
 				message.setType(2);
 				message.setState(0);
 				message.setOrgId(UserUtils.getOrgId());
 				Date date = new Date();
 				message.setCreateTime(date);
 				String msg = "有个预约单（投资人："+matchReqBean.getEmployeeName()+"）已经分配给你，请及时跟进";
 				message.setMessage(msg);
 				int result = messageLogServiceImpl.save(message);
 				if(result == 1){
 					LOGGER.error("message for allotEmp success");
 				}else{
 					LOGGER.error("message for allotEmp error");
 				}
    			//向机构员工pad端发送预约分配消息
     			MessagePush messagePush = new MessagePush(msg,"机构消息");
     			Set<String> alias = new HashSet<String>();
     			alias.add(matchReqBean.getEmployeeId());
     			messagePush.sendPushAlias(alias);
     			//向接收人发送短信
	    		SmsUtils.send(emp.getMobile(),msg);
			}
		} catch (Exception e) {
			LOGGER.error("allotEmp employee error, msg=[{}]", e.getMessage());
			bean.setMessage("预约单分配理财师失败："+e.getMessage());
		}
        return bean;
    }
		
	 /**
     * 获得预约单联系记录列表
     * @param model 参数
     * @return 联系记录List
     */
	@ResponseBody
    @RequestMapping("/queryRela")
    public Map<String, Object> queryRela(@RequestBody Appointment model) {
		Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		model.setOrderBy("visit_time desc");
    		List<RelationResBean> list = appointmentServiceImpl.queryRelation(model);
    		
    		// 统计的时候，不需要分页
    		model.setPage(null);
    		long totalRecord =list.size();
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("Investor query success.");
    		}
    		
    		// jQuery datatable 就是这样的参数，阿西吧
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("relation query error, msg=[{}]", e.getMessage());
		}
        return result;
    }
	
    /**
     * 跳转到编辑信息页面
     * @param model 查询参数，携带ID
     * @return 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(Appointment model, Map<String, Object> maps) {
        model = appointmentServiceImpl.get(model.getId());
        maps.put("model", model);
        return "appointment/edit";
    }
    
    /**
     * 查询理财师团队名称
     * @param model 查询参数，携带groupId
     * @return Jsonbean
     */
    @ResponseBody
    @RequestMapping("/queryEmpGroup")
    public JsonBean queryEmpGroup(@RequestBody Appointment model) {
    	JsonBean bean = new JsonBean();
    	try { 
    		String groups = model.getGroupId();
    		if (groups != null && !groups.equals("")) {
    			List<String> groupList = new ArrayList<String>();
    			String[] str = groups.split(",");
    			for (String string : str) {
    				groupList.add(string);
    			}
    			List<String> list = appointmentServiceImpl.getEmpGroup(groupList);
    			bean.setCode(1);
    			bean.setData(list);
    			bean.setMessage("查询理财师团队名称成功");
    		}
    		return bean;
		} catch (Exception e) {
			e.printStackTrace();
			bean.setCode(0);
			bean.setMessage("查询理财师团队名称失败");
		}
		return bean;
    }
}
